package com.anpy.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.anpy.common.service.BaseServiceImpl;
import com.anpy.common.service.model.vo.Result;
import com.anpy.common.service.utils.RedisUtils;
import com.anpy.common.service.utils.TokenUtils;
import com.anpy.user.entity.LoginRequestVO;
import com.anpy.user.entity.UserEntity;
import com.anpy.user.enumtype.LoginEnum;
import com.anpy.user.mapper.UserMapper;
import com.anpy.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service("userServiceImpl")
public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserEntity> implements UserService {

    // 默认密码
    private static final String DEFAULT_PASSWORD = "anpy123456";

    @Override
    public boolean saveUserInfo(UserEntity userEntity) {
        // 如果没有设置密码，则设置默认密码
        if (StrUtil.isEmpty(userEntity.getPassword())) {
            userEntity.setPassword(DEFAULT_PASSWORD);
        }
        return save(userEntity);
    }

    @Override
    public UserEntity loadUserInfo(Integer userId) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getId, userId);
        return this.getOne(wrapper);
    }

    @Override
    public boolean uploadUserInfo(UserEntity userEntity) {
        LambdaUpdateWrapper<UserEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(UserEntity::getHeaderPhoto, userEntity.getHeaderPhoto());
//        wrapper.set(UserEntity::getHeaderPhoto,userEntity.getHeaderPhoto());
        wrapper.eq(UserEntity::getId, userEntity.getId());
        return update(wrapper);
    }

    @Override
    public UserEntity loadCacheData(String phone) {
        String user = (String) RedisUtils.get(phone + "user");
        if (StrUtil.isEmpty(user)) {
            synchronized (this) {
                LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(UserEntity::getPhone, phone);
                UserEntity one = this.getOne(wrapper);

                RedisUtils.set(phone + "user", JSON.toJSONString(one), 1000 * 60 * 60 * 24 * 7);
                return one;
            }
        }

        return JSON.parseObject(user, new TypeReference<UserEntity>() {
        });
    }

    @Override
    public UserEntity login(LoginRequestVO loginRequest) {
        switch (Objects.requireNonNull(LoginEnum.getLoginType(loginRequest.getLoginType()))) {
            case PASSWORD:
                // 用户名密码登录
                if (ObjectUtils.isNotEmpty(loginRequest.getPhone()) && ObjectUtils.isNotEmpty(loginRequest.getPassword())) {
                    LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(UserEntity::getPhone, loginRequest.getPhone());
                    UserEntity user = this.getOne(wrapper);
                    
                    // 用户不存在，返回null
                    if (user == null) {
                        return null;
                    }
                    
                    // 密码不匹配，返回null
                    if (!loginRequest.getPassword().equals(user.getPassword())) {
                        return null;
                    }
                    
                    // 账号密码匹配，生成token并返回
                    user.setToken(TokenUtils.createLinkToken(user.getId().toString()));
                    return user;
                }
                break;
            case WX:
                // 微信登录
                break;
            case WB:
                // 微博登录
                break;
            default:
                return null;
        }
        return null;
    }

    @Override
    public List<UserEntity> getAllUsers() {
        // 直接返回所有用户列表
        return list();
    }

    @Override
    public Page<UserEntity> getUsersByPage(int page, int size, String userName, String phone) {
        // 构建查询条件
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果有用户名参数，添加模糊查询条件
        if (StrUtil.isNotEmpty(userName)) {
            queryWrapper.like(UserEntity::getUserName, userName);
        }
        
        // 如果有手机号参数，添加模糊查询条件
        if (StrUtil.isNotEmpty(phone)) {
            queryWrapper.like(UserEntity::getPhone, phone);
        }
        
        // 按ID降序排序
        queryWrapper.orderByDesc(UserEntity::getId);
        
        // 执行分页查询
        return page(new Page<>(page, size), queryWrapper);
    }
}
